<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-center">
      <el-row class="jsbos-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <div class="jsbos-common-search-box-left">
            <el-col :span="4">
              <el-form-item label="名称">
                <el-input
                  v-model="query.name"
                  placeholder="请输入"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <template v-if="showAll">
              <el-col :span="4">
                <el-form-item label="课程目录">
                  <TreeSelect
                    v-model="query.category"
                    placeholder="请选择
                                        "
                    :options="categoryOptions"
                    :props="categoryProps"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="可见范围">
                  <el-select
                    v-model="query.scopeType"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in scopeOptions"
                      :key="index"
                      :label="item.fullName"
                      :value="item.id"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="状态">
                  <el-select
                    v-model="query.enabledMark"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in enabledMarkOptions"
                      :key="index"
                      :label="item.fullName"
                      :value="item.id"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="标签">
                  <el-select
                    v-model="query.label"
                    placeholder="请选择标签"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in labelOptions"
                      :key="index"
                      :label="item.fullName"
                      :value="item.enCode"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="4">
              <el-form-item label="">
                <el-checkbox v-model="query.myCreated" @change="search()"
                  >只看我创建的</el-checkbox
                >
              </el-form-item>
            </el-col>
          </div>
          <div>
            <el-col :span="4" style="min-width: 230px">
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="search()"
                  >查询</el-button
                >
                <el-button icon="el-icon-refresh-right" @click="reset()"
                  >重置</el-button
                >
                <el-button
                  type="text"
                  icon="el-icon-arrow-down"
                  @click="showAll = true"
                  v-if="!showAll"
                >
                  展开
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-arrow-up"
                  @click="showAll = false"
                  v-else
                >
                  收起
                </el-button>
              </el-form-item>
            </el-col>
          </div>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addOrUpdateHandle()"
              >新增
            </el-button>
            <el-button type="text" icon="el-icon-download" @click="exportData()"
              >导出
            </el-button>
          </div>
          <div class="jsbos-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JSBOS-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <screen-full isContainer />
            <el-tooltip effect="dark" content="列设置" placement="top">
              <el-link
                icon="icon-ym icon-ym-options jsbos-common-head-icon"
                :underline="false"
                @click="() => this.$refs.jsbosTableRef.showDrawer()"
              />
            </el-tooltip>
          </div>
        </div>
        <jsbos-table
          v-loading="listLoading"
          :data="list"
          ref="jsbosTableRef"
          @sort-change="sortChange"
        >
          <el-table-column prop="name" label="名称" width="0" align="left">
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="goDetail(scope.row.id)"
                >{{ scope.row.name }}</el-link
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="category"
            label="课程目录"
            width="200"
            align="center"
          />
          <el-table-column
            label="可见范围"
            width="100"
            prop="scopeType"
            algin="center"
          >
            <template slot-scope="scope">
              {{ scope.row.scopeType | dynamicText(scopeOptions) }}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            width="100"
            prop="enabledMark"
            algin="center"
          >
            <template slot-scope="scope">
              {{ scope.row.enabledMark | dynamicText(enabledMarkOptions) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="creatorUserId"
            label="创建用户"
            width="120"
            align="center"
          />
          <el-table-column
            prop="creatorTime"
            label="创建时间"
            width="150"
            align="center"
          />
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="goDataDetail(scope.row.id)"
                >数据
              </el-button>
              <el-button
                type="text"
                :disabled="scope.row.enabledMark == 20"
                @click="addOrUpdateHandle(scope.row.id)"
                >编辑
              </el-button>
              <el-dropdown>
                <span class="el-dropdown-link">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-if="scope.row.enabledMark == 20"
                    @click.native="handleUnpublish(scope.row.id)"
                    >取消发布</el-dropdown-item
                  >
                  <el-dropdown-item
                    @click.native="handleUpdateScope(scope.row.id)"
                    >可见范围</el-dropdown-item
                  >
                  <el-dropdown-item @click.native="createQrcode(scope.row)"
                    >学习二维码</el-dropdown-item
                  >
                  <el-dropdown-item @click.native="handleDel(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                  <el-dropdown-item @click.native="goDetail(scope.row.id)"
                    >详情</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JSBOS-Form v-if="formVisible" ref="JSBOSForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <Detail
      v-if="detailVisible"
      ref="Detail"
      @refresh="detailVisible = false"
    />
    <CourseData
      v-if="dataDetailVisible"
      ref="CourseDataDetail"
      @refresh="dataDetailVisible = false"
    />
    <UpdateScope v-if="scopeVisible" ref="updateScope" @refresh="refresh" />
    <el-dialog
      :title="qrDialogName"
      :visible.sync="qrcodeVisible"
      :close-on-click-modal="false"
      class="jsbos-dialog jsbos-dialog_center"
      lock-scroll
      width="600px"
    >
      <div class="qr_create">
        <div
          :id="'qrCode'"
          :ref="'qrCode'"
          :data-code="qrCode"
          style="
            width: 300px;
            height: 300px;
            border: 1px solid #eee;
            margin-bottom: 24px;
            margin-left: 24px;
          "
        ></div>
        <!-- 作为下载二维码使用 -->
        <a ref="downLoadImgUrl" style="display: none"></a>
      </div>
      <div class="qr_create_httpUrl">链接地址：{{ httpCourseMUrl }}</div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="qrcodeVisible = false">取 消</el-button>
        <el-button type="primary" @click="downQrcodeImg">下载二维码</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import JSBOSForm from "./Form";
import ExportBox from "./ExportBox";
import Detail from "./Detail";
import CourseData from "./CourseData";
import UpdateScope from "./UpdateScope";
import QRCode from "qrcodejs2";

export default {
  components: { JSBOSForm, ExportBox, Detail, CourseData, UpdateScope },
  data() {
    return {
      qrcodeVisible: false,
      qrCode: "",
      qrDialogName: "",
      qrcodeImgUrl: "",
      sysAddress: "",
      httpCourseMUrl: "",
      showAll: false,
      detailVisible: false,
      dataDetailVisible: false,
      scopeVisible: false,
      query: {
        category: undefined,
        myCreated: false,
        scope: undefined,
        enabledMark: undefined,
        name: undefined,
        label: undefined,
      },
      treeProps: {
        children: "children",
        label: "fullName",
        value: "id",
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      },
      formVisible: false,
      exportBoxVisible: false,
      columnList: [
        { prop: "category", label: "课程目录" },
        { prop: "name", label: "名称" },
        { prop: "scopeType", label: "可见范围" },
        { prop: "enabledMark", label: "状态" },
        { prop: "creatorUserId", label: "创建用户" },
        { prop: "creatorTime", label: "创建时间" },
      ],
      categoryOptions: [],
      categoryProps: {
        label: "name",
        value: "id",
        children: "children",
      },
      labelOptions: [],
      labelProps: {
        label: "fullName",
        value: "enCode",
      },
      scopeOptions: [
        { fullName: "全公司", id: "all" },
        { fullName: "仅创建人", id: "creator" },
        {
          fullName: "指定人员",
          id: "select",
        },
      ],
      scopeProps: {
        label: "fullName",
        value: "id",
      },
      evaluationOptions: [
        { fullName: "星评", id: "1" },
        { fullName: "评估表", id: "2" },
      ],
      evaluationProps: {
        label: "fullName",
        value: "id",
      },
      preventionCheatOptions: [{ fullName: "开启", id: "1" }],
      preventionCheatProps: {
        label: "fullName",
        value: "id",
      },
      lastModifyUserIdOptions: [{ fullName: "开启", id: "1" }],
      lastModifyUserIdProps: {
        label: "fullName",
        value: "id",
      },
      enabledMarkOptions: [
        { fullName: "待发布", id: "10" },
        { fullName: "已发布", id: "20" },
      ],
      enabledMarkProps: {
        label: "fullName",
        value: "id",
      },
    };
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.initData();
    this.getCategoryOptions();
    this.getLabelOptions();
  },
  methods: {
    getCategoryOptions() {
      request({
        url: "/api/course/TemsCourseCatalog/Selector",
        method: "get",
      }).then((res) => {
        let data = [];
        let topItem = {
          name: "全部",
          hasChildren: true,
          id: "-1",
          children: res.data.list,
        };
        this.categoryOptions = data.concat(topItem);
      });
    },
    getLabelOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "CoureseMark",
        })
        .then((res) => {
          this.labelOptions = res;
        });
    },
    goDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    goDataDetail(id) {
      this.dataDetailVisible = true;
      this.$nextTick(() => {
        this.$refs.CourseDataDetail.init(id);
      });
    },

    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/course/TemsCourse/getList`,
        method: "post",
        data: _query,
      }).then((res) => {
        var _list = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i];
          _list.push(_data);
        }
        this.list = _list;
        this.total = res.data.pagination.total;

        this.listLoading = false;
      });
    },
    handleUnpublish(id) {
      this.$confirm(
        "取消发布后学员在学习界面将看不到当前课程了，确定要取消发布吗？",
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          request({
            url: `/api/course/TemsCourse/unpublish/${id}`,
            method: "PUT",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          request({
            url: `/api/course/TemsCourse/${id}`,
            method: "DELETE",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JSBOSForm.init(id, isDetail);
      });
    },
    handleUpdateScope(id) {
      this.scopeVisible = true;
      this.$nextTick(() => {
        this.$refs.updateScope.init(id);
      });
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = {
        ...data,
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/course/TemsCourse/Actions/Export`,
        method: "GET",
        data: query,
      }).then((res) => {
        if (!res.data.url) return;
        this.jsbos.downloadFile(res.data.url);
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.query.myCreated = false;
      this.search();
    },

    getSystemAddress() {
      getSystemAddress("app").then((res) => {
        this.sysAddress = res.msg;
      });
    },
    createQrcode(row) {
      this.qrcodeVisible = true;
      if (!row) {
        return;
      }
      this.qrDialogName = "【" + row.name + "】课程二维码";
      const baseUrl = this.sysAddress.substring(
        0,
        this.sysAddress.indexOf("#")
      );
      this.httpCourseMUrl = baseUrl + "/#/pages/course/detail?id=" + row.id;
      this.$nextTick(() => {
        const qrCodeRef = this.$refs["qrCode"];
        if (qrCodeRef) {
          qrCodeRef.innerHTML = ""; // 清空二维码容器
          new QRCode(qrCodeRef, {
            width: 300,
            height: 300,
            text: this.httpCourseMUrl,
            correctLevel: QRCode.CorrectLevel.M,
          });
          let qrcodeCanvas =
            this.$refs.qrCode.getElementsByTagName("canvas")[0];
          this.qrcodeImgUrl = qrcodeCanvas.toDataURL("image/png"); // 作为下载图片资源
        } else {
          console.error("QRCode ref is not defined");
        }
      });
    },
    // 下载二维码
    downQrcodeImg() {
      let downloadLink = this.$refs.downLoadImgUrl;
      downloadLink.setAttribute("href", this.qrcodeImgUrl);
      downloadLink.setAttribute(
        "download",
        `${this.qrDialogName}_${new Date().getTime()}.png`
      );
      downloadLink.click();
      URL.revokeObjectURL(downloadLink.href);
      this.qrcodeVisible = false;
    },
  },
};
</script>
<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
}

.el-icon-arrow-down {
  font-size: 12px;
}
.qr_create {
  width: 100%;
  display: flex;
  justify-content: center;
}
.qr_create_httpUrl {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
</style>
